package cn.javaxc.mvcwork.controller;
import cn.javaxc.mvcwork.framework.actions.TActionContext;
import java.util.HashMap;
import javax.servlet.http.*;





public class SessionManager {

  public final static int ADD = 1;
  public final static int REMOVE = 2;
  HashMap<Object,UserSession> sessions = new HashMap();


  
  public SessionManager() {
  }


  
  public void setSessions(HashMap sessions) {
    this.sessions = sessions;
  }


  
  public HashMap getSessions() {
    return sessions;
  }


  
//  public void addUser(TActionContext context, Object userId) {
//    this.addUser(context.getRequest(), userId);
//  }


  
  public void addUser(HttpSession session,Object userId) {
//    HttpSession session = request.getSession();
    UserSession thisSession = new UserSession();
    thisSession.setId(session.getId());
//    thisSession.setIpAddress(ip);
    thisSession.setCreationTime(session.getCreationTime());
    thisSession.setUserId(userId);
    if (sessions.get(userId) == null) {
      synchUpdate(thisSession, userId, ADD);
    } else {
      if (System.getProperty("DEBUG") != null) {
        System.out.println(
            "SessionManager-> User " + userId + " already has a session");
      }
    }
  }


  
  public void synchUpdate(UserSession thisSession, Object userId, int action) {
    synchronized (this) {
      if (action == ADD) {
        sessions.put(userId, thisSession);
        if (System.getProperty("DEBUG") != null) {
          System.out.println("SessionManager-> User " + userId + " Added");
        }
      } else if (action == REMOVE) {
        sessions.remove(userId);
        if (System.getProperty("DEBUG") != null) {
          System.out.println("SessionManager-> User " + userId + " Removed");
        }
      }
    }
  }


  
  public void removeUser(Object userId) {
    UserSession thisSession = (UserSession) sessions.get(userId);
    if (thisSession != null) {
      synchUpdate(thisSession, userId, REMOVE);
    }
  }


  
  public boolean isUserLoggedIn(Object userId) {
    return sessions.containsKey(userId);
  }


  
  public UserSession getUserSession(Object userId) {
    if (sessions.get(userId) != null) {
      return (UserSession) sessions.get(userId);
    }
    return null;
  }


  
  public UserSession replaceUserSession(HttpSession session, Object userId) {
    removeUser(userId);
    addUser(session, userId);
    return getUserSession(userId);
  }


  
  public int size() {
    return sessions.size();
  }
}
